package com.lq.rabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 配置 rabbitmq的回调
 */
@Component
@Slf4j
public class ConfimDaick implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     *   @PostConstruct 这是一个 后构造器注解
     */
    @PostConstruct
    public void init(){
         rabbitTemplate.setConfirmCallback(this);
         rabbitTemplate.setReturnCallback(this);
    }

    /**
     *  rabbitmq  接收到回调 没有接收也要回调
     * @param correlationData
     * @param b
     * @param s
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        String id=correlationData!=null?correlationData.getId():"";
        if (b) {
          log.info("接收成功回调id{}",id);
        }else{
            log.info("接收失败:{},id:",s,id);
        }
    }

    /**
     *  传递信息过程中 失败了 回调
     * @param message 信息内容
     * @param i
     * @param s
     * @param s1   失败原因
     * @param s2  路由key
     */
    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
        log.error("信息{},被交换机退回，退回的原因{}，路由key {} ",new String(message.getBody()),s1,s2);
    }
}
